import React, { useState, useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { saveAs } from 'file-saver'; // 需要安装 file-saver
import * as XLSX from 'xlsx';
import '../../pages/promote/index.css';

const ReportModal = ({ visible, onClose }) => {
  const [dateRange, setDateRange] = useState('week');
  const [loading, setLoading] = useState(false);
  const [currentData, setCurrentData] = useState(null); // 存储当前数据用于导出
  const chartRef = useRef(null);
  let myChart = null;

  // 弹窗显示时初始化图表
  useEffect(() => {
    if (visible) {
      fetchReportData();
      if (chartRef.current) {
        myChart = echarts.init(chartRef.current);
      }
    }
    return () => {
      if (myChart) {
        myChart.dispose();
        myChart = null;
      }
    };
  }, [visible, dateRange]);

  // 模拟请求报表数据
  const fetchReportData = () => {
    setLoading(true);
    setTimeout(() => {
      const mockData = {
        day: {
          labels: ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00'],
          values: [120, 80, 60, 150, 280, 320, 250, 180],
          stats: { totalPromote: 2586, validConversions: 856, totalIncome: 86520 }
        },
        week: {
          labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          values: [1200, 1900, 1500, 2800, 3200, 4500, 3800],
          stats: { totalPromote: 2586, validConversions: 856, totalIncome: 86520 }
        },
        month: {
          labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
          values: [12000, 15000, 18000, 16000, 22000, 28000],
          stats: { totalPromote: 2586, validConversions: 856, totalIncome: 86520 }
        }
      };
      setCurrentData(mockData[dateRange]);
      renderChart(mockData[dateRange]);
      setLoading(false);
    }, 800);
  };

  // 渲染 ECharts 图表
  const renderChart = (data) => {
    if (myChart && data) {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: data.labels,
          axisLabel: {
            color: '#5d4037'
          },
          axisLine: {
            lineStyle: {
              color: '#e0d8d0'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#5d4037',
            formatter: '¥{value}' // 显示货币符号
          },
          axisLine: {
            lineStyle: {
              color: '#e0d8d0'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0e8e2'
            }
          }
        },
        series: [
          {
            data: data.values,
            type: 'bar',
            barWidth: '40%',
            itemStyle: {
              color: '#8d6e63',
              borderRadius: [4, 4, 0, 0]
            },
            label: {
              show: true,
              position: 'top',
              formatter: '¥{c}',
              color: '#5d4037'
            }
          }
        ],
        grid: {
          left: '10%',
          right: '10%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        }
      };
      myChart.setOption(option);
    }
  };

  // 生成CSV内容
  const generateCSV = () => {
    if (!currentData) return null;
    
    // 标题行
    let csvContent = "时间段,收益(元)\n";
    
    // 数据行
    currentData.labels.forEach((label, index) => {
      csvContent += `${label},${currentData.values[index]}\n`;
    });
    
    // 统计信息行
    csvContent += "\n统计信息,,\n";
    csvContent += `总推广人数,${currentData.stats.totalPromote},\n`;
    csvContent += `有效转化数,${currentData.stats.validConversions},\n`;
    csvContent += `总收益,${currentData.stats.totalIncome}元,\n`;
    
    return csvContent;
  };

  // 生成Excel数据
  const generateExcel = () => {
    if (!currentData) return null;
    
    // 准备数据
    const dataSheet = [
      ["时间段", "收益(元)"]
    ];
    
    // 添加数据行
    currentData.labels.forEach((label, index) => {
      dataSheet.push([label, currentData.values[index]]);
    });
    
    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(dataSheet);
    
    // 添加统计信息工作表
    const statsSheet = XLSX.utils.aoa_to_sheet([
      ["统计信息", "", ""],
      ["总推广人数", currentData.stats.totalPromote, ""],
      ["有效转化数", currentData.stats.validConversions, ""],
      ["总收益", `${currentData.stats.totalIncome}元`, ""]
    ]);
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "收益数据");
    XLSX.utils.book_append_sheet(wb, statsSheet, "统计信息");
    
    return wb;
  };

  // 导出CSV
  const exportCSV = () => {
    if (!currentData) return;
    
    const csvContent = generateCSV();
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const fileName = `数据报表_${getDateRangeText()}_${new Date().toLocaleDateString().replace(/\//g, '-')}.csv`;
    saveAs(blob, fileName);
  };

  // 导出Excel
  const exportExcel = () => {
    if (!currentData) return;
    
    const wb = generateExcel();
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    const fileName = `数据报表_${getDateRangeText()}_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`;
    saveAs(blob, fileName);
  };

  // 获取日期范围文本
  const getDateRangeText = () => {
    switch(dateRange) {
      case 'day': return '今日';
      case 'week': return '本周';
      case 'month': return '本月';
      default: return '';
    }
  };

  // 切换日期范围
  const handleDateRangeChange = (range) => {
    setDateRange(range);
  };

  if (!visible) return null;

  return (
    <div className="qr-modal-overlay">
      <div className="qr-modal report-modal">
        <div className="qr-modal-header">
          <h3>数据报表</h3>
          <button className="close-btn" onClick={onClose}>&times;</button>
        </div>
        
        <div className="qr-modal-content">
          {/* 日期范围选择 */}
          <div className="date-range-group">
            <button
              className={`date-range-btn ${dateRange === 'day' ? 'active' : ''}`}
              onClick={() => handleDateRangeChange('day')}
            >
              今日
            </button>
            <button
              className={`date-range-btn ${dateRange === 'week' ? 'active' : ''}`}
              onClick={() => handleDateRangeChange('week')}
            >
              本周
            </button>
            <button
              className={`date-range-btn ${dateRange === 'month' ? 'active' : ''}`}
              onClick={() => handleDateRangeChange('month')}
            >
              本月
            </button>
          </div>

          {/* 统计数据卡片 */}
          <div className="report-stats">
            <div className="report-stat-card">
              <p className="report-stat-label">总推广人数</p>
              <p className="report-stat-value">{currentData?.stats?.totalPromote || '0'}</p>
            </div>
            <div className="report-stat-card">
              <p className="report-stat-label">有效转化数</p>
              <p className="report-stat-value">{currentData?.stats?.validConversions || '0'}</p>
            </div>
            <div className="report-stat-card">
              <p className="report-stat-label">总收益</p>
              <p className="report-stat-value income">¥{currentData?.stats?.totalIncome.toLocaleString() || '0'}</p>
            </div>
          </div>

          {/* ECharts 图表容器 */}
          <div className="chart-container" style={{ height: '300px' }}>
            {loading ? (
              <div className="ai-loading-container">
                <div className="loading-spinner"></div>
                <p className="loading-text">加载数据中...</p>
              </div>
            ) : (
              <div ref={chartRef} style={{ width: '100%', height: '100%' }}></div>
            )}
          </div>
        </div>
        
        <div className="qr-modal-footer">
          <button 
            className="export-btn" 
            onClick={exportCSV}
            disabled={!currentData}
          >
            导出CSV
          </button>
          <button 
            className="export-btn" 
            onClick={exportExcel}
            disabled={!currentData}
          >
            导出Excel
          </button>
        </div>
      </div>
    </div>
  );
};

export default ReportModal;
